package com.xuanwoa.rabbit.guava.concurrent;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.RandomUtil;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Description
 *
 * @author caomin
 * @since 2021/1/20
 */
public class ListenableFutureDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ListeningExecutorService service = MoreExecutors.listeningDecorator(executorService);
        ListenableFuture future = service.submit(() -> {
            try {
                Thread.sleep(300);
                return RandomUtil.randomString(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            }
        });
        future.addListener(() -> {
            TimeInterval timer = DateUtil.timer();
            System.out.println("complete");
            try {
                Console.log("获取future值[{}]", future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            Console.log("花费时间[{}]ms", timer.interval());
            service.shutdown();
        }, service);

    }
}
